package com.example.demo.usermanage.controller;

import com.example.demo.usermanage.dao.UserMapper;
import com.example.demo.usermanage.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zplogo on 2017/5/18.
 *
 */
@Controller
@RequestMapping("user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserMapper userMapper;

    /**
     *
     * ModelAttribute注解的方法会优先该类其他方法执行，用于组装Model或者ModelAndView
     *
     */
    @ModelAttribute
    public void userModel(@RequestParam(value="username",defaultValue = "Timi") String username,
                          @RequestParam(value="password",defaultValue = "123456") String password,ModelAndView mv){
        User user = new User();
        user.setUserName(username);
        user.setPassword(password);
        mv.addObject(user);
    }

    /**
     * http://localhost:8080/user/main.do
     */
    @RequestMapping(value = "main",method = RequestMethod.GET)
    public String jumpToMainPage(Model model){
        User user = new User();
        user.setUserName("张三");
        model.addAttribute("user",user);
        return "WEB-INF/main";
    }

    /**
     * @param mv ModelAttribute注解方法传递过来ModelAndView对象，赋值给形参mv
     * @return 包含数据和视图的mv对象/
     */
    @RequestMapping("/insertUser")
    public ModelAndView insertUser(ModelAndView mv){
        User user = (User)mv.getModel().get("user");
        user.setSex("女");
        logger.info("zplogo===" + user.toString());
        userMapper.insert(user);
        mv.setViewName("WEB-INF/main");
        return mv;
    }

    /**
     * http://localhost:8080/user/queryUserList.do
     */
    @RequestMapping("/queryUserList")
    public ModelAndView queryUserList(ModelAndView mv){
        List<User> userList = userMapper.queryUserList();
        mv.addObject("userList",userList);
//      模拟Map数据
        User user1 = new User("测试一","123");
        User user2 = new User("test2","456");
        Map userMap = new HashMap();
        userMap.put(1,user1);
        userMap.put(2,user2);
        mv.addObject("userMap",userMap);
        mv.setViewName("userList");
        return mv;
    }
}
